import router from "@/router";

let ability = {};
try {
  let data = sessionStorage.getItem("ability");
  ability = (data && JSON.parse(data)) || {};
} catch (e) {
  console.log(e);
}

/**
 * 过滤权限按钮
 * @param {*} list Array
 * @returns
 */
const filterAbility = (list) => {
  if (!list || !list.length) return {};
  let ability = {};
  list.map((item) => {
    if (item.childList?.length) {
      Object.assign(ability, filterAbility(item.childList));
    }
    if (item.ability && Object.keys(item.ability)?.length) {
      ability[item.requestPath] = item.ability;
    }
  });
  return ability;
};

const permission = {
  bind(el, { value }) {
    let path = router.history?.current?.path || "";
    if (!path || !value || !ability[path]?.[value]) {
      el.innerHTML = "";
      return;
    }
  }
};

export default {
  install(Vue) {
    Vue.prototype.$setAbility = function (list = []) {
      try {
        ability = filterAbility(list);
        sessionStorage.setItem("ability", JSON.stringify(ability));
      } catch (e) {
        console.log(e);
      }
    };
    Vue.directive("permission", permission);
  }
};
